<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="分类名称" prop="catalogName">
				<el-input v-model="queryParams.catalogName" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="Plus" @click="handleAdd"
					v-hasPermi="['base:catalog:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
			</el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['base:catalog:export']">导出</el-button>
      </el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-if="refreshTable" v-loading="loading" :data="catalogList" row-key="catalogId"
			:default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
<!--            <el-table-column label="序号" align="center" width="55">-->
<!--              <template  #default="scope">{{scope.$index+1}}</template>-->
<!--            </el-table-column>-->
			<el-table-column label="分类名称" align="center" prop="catalogName"  />
      <el-table-column label="户号名称" align="center" prop="typeName" />
<!--			<el-table-column label="显示顺序" align="center" prop="orderNum" />-->
			<el-table-column label="状态" align="center" prop="status" width="100">
				<template #default="scope">
					<dict-tag :options="status" :value="scope.row.status" />
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template #default="scope">
					<el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['base:catalog:edit']">修改</el-button>
					<el-button type="text" icon="Plus" @click="handleAdd(scope.row)"
						v-hasPermi="['base:catalog:add']">新增</el-button>
					<el-button type="text" icon="Delete" @click="handleDelete(scope.row)"
						v-hasPermi="['base:catalog:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加或修改分类对话框 -->
		<el-dialog :title="title" v-model="open" width="500px" append-to-body>
			<el-form ref="catalogRef" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="上级分类" prop="parentId">
					<el-tree-select v-model="form.parentId" :data="catalogOptions"
						:props="{ value: 'catalogId', label: 'catalogName', children: 'children' }" value-key="catalogId"
						placeholder="请选择上级分类" check-strictly />
				</el-form-item>
				<el-form-item label="分类名称" prop="catalogName">
					<el-input v-model="form.catalogName" placeholder="请输入分类名称" />
				</el-form-item>
        <el-form-item label="户号分类" prop="TypeName">
          <el-input v-model="form.catalogName" placeholder="户号分类" />
        </el-form-item>
				<el-form-item label="显示顺序" prop="orderNum">
					<el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="form.status" placeholder="请选择状态">
						<el-option v-for="dict in status" :key="dict.value" :label="dict.label"
							:value="parseInt(dict.value)"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>

    <!-- 档案分类导入对话框 -->
    <el-dialog v-loading.fullscreen.lock="fullscreenLoading" :title="upload.title" v-model="upload.open" width="400px"
               append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的分类管理
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
	</div>
</template>

<script setup name="Catalog">
import {
  getToken
} from "@/utils/auth";
import {
	listCatalog,
	getCatalog,
	delCatalog,
	addCatalog,
	updateCatalog
} from "@/api/base/catalog";
import {getCurrentInstance, reactive, ref} from "vue";

const {
	proxy
} = getCurrentInstance();
const {
	status,
	is_delflag
} = proxy.useDict('status', 'is_delflag');

const catalogList = ref([]);
const catalogOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);
const fullscreenLoading = ref(false);
/*** 分类导入参数 */
const upload = reactive({
  // 是否显示弹出层（档案分类导入）
  open: false,
  // 弹出层标题（档案分类导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken()
  },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/base/catalog/importData"
});
/** 下载模板操作 */
function importTemplate() {
  proxy.download("base/catalog/importTemplate", {}, `分类管理导入模板.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
  fullscreenLoading.value = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  fullscreenLoading.value = false;
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg +
      "</div>", "导入结果", {
    dangerouslyUseHTMLString: true
  });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

const data = reactive({
	form: {},
	queryParams: {
		parentId: null,
		catalogName: null,
		orderNum: null,
	},
	rules: {
		parentId: [{
			required: true,
			message: "上级分类不能为空",
			trigger: "blur"
		}],
		catalogName: [{
			required: true,
			message: "分类名称不能为空",
			trigger: "blur"
		}],
		status: [{
			required: true,
			message: "状态不能为空",
			trigger: "blur"
		}],
	}
});

const {
	queryParams,
	form,
	rules
} = toRefs(data);

/** 查询分类列表 */
function getList() {
	loading.value = true;
	listCatalog(queryParams.value).then(response => {
		catalogList.value = proxy.handleTree(response.data, "catalogId", "parentId");
		loading.value = false;
	});
}

/** 查询分类下拉树结构 */
function getTreeselect() {
	listCatalog().then(response => {
		catalogOptions.value = [];
		const data = {
			catalogId: 0,
			catalogName: '顶级节点',
			children: []
		};
		data.children = proxy.handleTree(response.data, "catalogId", "parentId");
		catalogOptions.value.push(data);
	});
}

// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		catalogId: null,
		parentId: null,
		catalogName: null,
		orderNum: null,
		status: null,
		delflag: null
	};
	proxy.resetForm("catalogRef");
}

/** 搜索按钮操作 */
function handleQuery() {
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm("queryRef");
	handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
	reset();
	getTreeselect();
	if (row != null && row.catalogId) {
		form.value.parentId = row.catalogId;
	} else {
		form.value.parentId = 0;
	}
	open.value = true;
	title.value = "添加分类";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
	refreshTable.value = false;
	isExpandAll.value = !isExpandAll.value;
	nextTick(() => {
		refreshTable.value = true;
	});
}

/** 修改按钮操作 */
async function handleUpdate(row) {
	reset();
	await getTreeselect();
	if (row != null) {
		form.value.parentId = row.catalogId;
	}
	getCatalog(row.catalogId).then(response => {
		form.value = response.data;
		console.log(form.value);
		open.value = true;
		title.value = "修改分类";
	});
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs["catalogRef"].validate(valid => {
		if (valid) {
			if (form.value.catalogId != null) {
				updateCatalog(form.value).then(response => {
					proxy.$modal.msgSuccess("修改成功");
					open.value = false;
					getList();
				});
			} else {
				addCatalog(form.value).then(response => {
					proxy.$modal.msgSuccess("新增成功");
					open.value = false;
					getList();
				});
			}
		}
	});
}

/** 删除按钮操作 */
function handleDelete(row) {
	proxy.$modal.confirm('是否确认删除分类编号为"' + row.catalogId + '"的数据项？').then(function () {
		return delCatalog(row.catalogId);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess("删除成功");
	}).catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/catalog/export', {
    ...queryParams.value
  }, `档案分类_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "分类导入";
  upload.open = true;
};
getList();
</script>
